<?php
namespace Nawa\MedicalStudy;
/**
 * Authorization Check Customize for Medical Studies
 * As in Nawa Medical Studies are consider as a subset of object
 * that cannot be handle the same way depending on who you are
 *
 */
use Nawa\Messages;

class Authorization {

	/**
	 * Admin Profile Id
	 * @var int
	 */
	const ADMIN_ID =  45;

	/**
	 *
	 * Admin Profile Name
	 * @var string
	 */
	const ADMIN_PROFILE_NAME =  'Nawa-Administrator';

	/**
	 *
	 * Admin Profile Name
	 * @var string
	 */
	const ROLE_ADMIN =  'ADM';

	/**
	 * Can Update Medical Studies
	 * @var string
	 */
	const MS_UPDATE = 'nawa-ms-update';

	/**
	 * Can the user view this Medical Studies (it means the user is
	 * a parnter of this medical study )
	 * @var string
	 */
	const MS_VIEW = 'nawa-ms-view';

	/**
	 *
	 * For Performance reason we set a transaction cache on MS Partners
	 * @var array
	 */
	private static $_msPatnersRole = array();

	/**
	 *
	 * Check if Authorization is in medical partner role
	 * @param string $authorizationName	Authorization Name
	 * @param int 	$medicalStudyId		Medical Study Id
	 * @param int 	$medicalCenterId	Medical Center Id
	 *  @return bool
	 */
	public static function check($authorizationName,$medicalStudy,$medicalCenterId = null) {

		$medicalStudyId = $medicalStudy->getId();
		if(!isset(self::$_msPatnersRole[$medicalStudyId])) {
			$userid = \User::current()->getId();
			// Load User Profile in Corresponding Subset
			$contact =  \User::current()->contact();
			$contactid = $contact->getId();
			self::$_msPatnersRole[$medicalStudyId] = $contact->findMedicalStudiesPartners($medicalStudyId.':'.$contactid);
		}
		$msp = self::$_msPatnersRole[$medicalStudyId];
		if(empty($msp) || !$msp->exists())
		{
			
			$userid = \User::current()->getId();
			
			if($medicalStudy->cname == $userid ) {
				return true;
			}
			
			// Check who is the administrator of the MS
			$admins = $medicalStudy->findAdministrators();
			if(count($admins) > 0) {
				$names = null;
				foreach($admins as $admin) {
					$names .=' '.$admin->name();
				}
				\Fox\Message::Error(Msg(Messages::BUNDLE,Messages::MSG_NO_ACCESS_CONTACT_ADMIN,$names));
			}
			return false;
		}
		// If the user is an administrator always return true
		if($msp->role == self::ROLE_ADMIN) {

			return true;
		}
		// Get Nawa Profile from partner Role

		// Check if Authorization is in current Profile

		return true;
	}

	/**
	 * Check if the User is an admin
	 */
	public function isAmdin($profileIdorName) {
		if($profileIdorName == self::ADMIN_ID || $profileIdorName == self::ADMIN_PROFILE_NAME) {
			return true;
		}
		return false;
	}
}